package com.ruoyi.web.controller.check;


import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.check.domain.*;
import com.ruoyi.check.service.*;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.ISysDeptService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;
import static com.ruoyi.generator.util.UnZipFileUtils.unZipFiles;
import static com.ruoyi.web.controller.tool.Copy.show;

/**
 * 自动生成表详情Controller
 *
 * @author hugh.sun
 * @date 2023-03-03
 */
@RestController
@RequestMapping("/check/automatic")
public class SysAutomaticController extends BaseController{

    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private IECheckListFormNameService eCheckListFormNameService;

    @Autowired
    private IECheckListFormItemService  ieCheckListFormItemService;

    @Autowired
    private IECheckListFormSubItemService ieCheckListFormSubItemService;



    @Autowired
    private ISysAutomaticService sysAutomaticService;

    @Log(title = "检点", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<NewCheck> util = new ExcelUtil<>(NewCheck.class);
        //new一个map集合k是表名 对应的每一张表对应很多数据
        HashMap<String, List<NewCheck>> map = new HashMap<>();

        List<NewCheck> userList = util.importExcel(file.getInputStream());
      List<String> strings = new ArrayList<>();
        userList.forEach(i->{
            String bname = i.getBname();
            strings.add(bname);
        });
        //所有的表名
        List<String> list = eCheckListFormNameService.everyName();


        if(Collections.disjoint(strings,list) ){

        userList.forEach((i)->{
            //1.如果名字相同就存到同一个map之中
            if(map.containsKey(i.getBname())){

                List<NewCheck> newChecks = map.get(i.getBname());
                NewCheck newCheck = new NewCheck();
                newCheck.setTiname(i.getTiname());
                newCheck.setZixuanxiang(i.getZixuanxiang());
                newCheck.setTitype(i.getTitype());
                newChecks.add(newCheck);

            }else {
                List<NewCheck> newChecks = new ArrayList<>();
                NewCheck newCheck = new NewCheck();
                newCheck.setTiname(i.getTiname());
                newCheck.setZixuanxiang(i.getZixuanxiang());
                newCheck.setTitype(i.getTitype());
                newChecks.add(newCheck);
                map.put(i.getBname(),newChecks);
            }
        });
        //删除状态默认为0
        try{
            //发布状态默认是 0 待发布
            map.forEach((i, k) -> {
                LoginUser loginUser = SecurityUtils.getLoginUser();
                String username = loginUser.getUsername();
                //部门
                Long deptId = loginUser.getDeptId();
                String deptName = deptService.selectDeptById(deptId).getDeptName();
                //流水号
                String s = DateUtils.getDate().toString();

                ECheckListFormName eCheckListFormName = new ECheckListFormName();
                //表名
                eCheckListFormName.setFormName(i);
                //流水号
                eCheckListFormName.setFormCode(s);
                //改变编码
                eCheckListFormName.setEcnNo("0");
                //默认是A
                eCheckListFormName.setRevsion("A");
                //部门
                eCheckListFormName.setDepartment(deptName);
                //创建人
                eCheckListFormName.setCreateUser(username);
                //创建时间
                eCheckListFormName.setCreateTime(new Date());
                //删除状态 初始值0 删除值1
                eCheckListFormName.setDelFlag(0L);
                //发布状态 默认为 0审核(待审核) 1 审核失败 2 审核成功
                eCheckListFormName.setPubFlag(0L);
                //插入表名
                eCheckListFormNameService.insertECheckListFormName(eCheckListFormName);

                //插入之后拿到最大的id

                //拿到id

                ECheckListFormItem item = new ECheckListFormItem();
                //拿到具体的参数
                List<NewCheck> k1 = k;

                k1.forEach(ki -> {
                    //现在存选项
                    String tiname = ki.getTiname();
                    Long titype = ki.getTitype();
                    String zixuanxiang = ki.getZixuanxiang();
                    //现在的split是子选项

                    item.setItemLabel(tiname);
                    item.setItemType(titype);
                    item.setCreateUser(username);
                    item.setCreateTime(new Date());
                    item.setItemRemark("");
                    item.setItemRestrict(0L);
                    long maxid = eCheckListFormNameService.maxid();
                    //题目id
                    item.setNameId(maxid);
                    ieCheckListFormItemService.insertECheckListFormItem(item);

                    long maxid1 = ieCheckListFormItemService.maxid();
                    String[] split = zixuanxiang.split("/");

                    ECheckListFormSubItem eCheckListFormSubItem = new ECheckListFormSubItem();
                    for (String ix :
                            split) {
                        if(!ix.equals("")) {
                            eCheckListFormSubItem.setSubItem(ix);
                            eCheckListFormSubItem.setItemId(maxid1);
                            ieCheckListFormSubItemService.insertECheckListFormSubItem(eCheckListFormSubItem);
                            //eCheckListFormSubItem.setItemId();
                        }
                    }

                });
            });
        }catch (Exception e){
            String message = e.getMessage();
            return error(message);
        }
        return success("导入成功！");
        }else
        {
            return  error("表已重复！请确认信息");
        }
    }



    @Log(title = "完成后端和前端复制配置功能")
    @GetMapping("/zip")
    public AjaxResult zip()  {
        //第一步将压缩文件复制到code下
        try {
            BufferedReader br = new BufferedReader(new FileReader("doc/configurations.txt"));
            String line1 = br.readLine();

            unZipFiles(line1,"code/");
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e+"controller中zip方式出错");
        } catch (IOException e) {
            throw new RuntimeException(e+"controller中zip方式出错");
        }

        //第二步将对应的文件复制到对应的位置
        //1.拷贝vue部分
        File filejs = new File("../code/yimeng/vue/api/check");
        // 路径 拿到js
        File[] js = filejs.listFiles();

        //路径 vue


        File filevue = new File("../code/yimeng/vue/views/check/");
        File[] vue = filevue.listFiles();
        File[] v = vue[0].listFiles();
        //拿java部分
        File filejava = new File("../code/yimeng/main/java/com/ruoyi/check/");
        List<File> show = show(filejava);
        File filexml = new File("../code/yimeng/main/resources/mapper/check/");
        //第一条记录Controller
        File Controller = show.get(0);
        //第二条记录domain
        File domain = show.get(1);
        //mapper
        File mapper = show.get(2);
        //service
        File service = show.get(3);
        //xml
        File[] filesxml = filexml.listFiles();
        File filex = filesxml[0];
        //


        //将对应的文件复制到具体位置上去
        //1.js

        Path sourcePathjs = Paths.get(js[0].getPath());

        Path targetDirPathjs = Paths.get("../ruoyi-ui/src/api/check");
        // 构造目标文件路径

        Path targetPathjs = targetDirPathjs.resolve(sourcePathjs.getFileName());
        // 使用Files.copy()方法进行文件复制
        try {
            Files.copy(sourcePathjs, targetPathjs);
        } catch (IOException e) {
            throw new RuntimeException(e+"zipcontroller中的copy");
        }

        //2.vue
        String path = v[0].getPath();
        String substring = path.substring(0, path.length() - 15);
        String sourceFolderPath = substring;

        //  System.out.println(sourceFolderPath+"vvvvvvvvvvvvvvvvvvvvvvvvvvv");
        String targetFolderPath = "../ruoyi-ui/src/views/check";
////        //将将test下的文件复制到亿蒙下面
        copyFolder(sourceFolderPath, targetFolderPath);
       //3.前端结束，下面是后端： 第一个xml
        Path sourcePathxml = Paths.get(filex.getPath());
        Path targetDirPathxml = Paths.get("../ruoyi-check/src/main/resources/mapper/check");
        // 构造目标文件路径
        Path targetPathxml = targetDirPathxml.resolve(sourcePathxml.getFileName());

        try {
            Files.copy(sourcePathxml, targetPathxml);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //4.controller
        Path sourcePathcon = Paths.get(Controller.getPath());
        Path targetDirPathcon = Paths.get("../ruoyi-admin/src/main/java/com/ruoyi/web/controller/check");
        // 构造目标文件路

        Path targetPathcon = targetDirPathcon.resolve(sourcePathcon.getFileName());

        try {
            Files.copy(sourcePathcon, targetPathcon);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //domain
        Path sourcePathpojo = Paths.get(domain.getPath());
        Path targetDirPathpojo = Paths.get("../ruoyi-check/src/main/java/com/ruoyi/check/domain");
        // 构造目标文件路

        Path targetPathpojo = targetDirPathpojo.resolve(sourcePathpojo.getFileName());

        try {
            Files.copy(sourcePathpojo, targetPathpojo);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


        //mapper
        Path sourcePathmapper = Paths.get(mapper.getPath());
        Path targetDirPathmapper = Paths.get("../ruoyi-check/src/main/java/com/ruoyi/check/mapper");

        Path targetPathmapper = targetDirPathmapper.resolve(sourcePathmapper.getFileName());

        try {
            Files.copy(sourcePathmapper, targetPathmapper);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //service
        Path sourcePathservice = Paths.get(service.getPath());
        Path targetDirPathservice = Paths.get("../ruoyi-check/src/main/java/com/ruoyi/check/service");

        Path targetPathservice = targetDirPathservice.resolve(sourcePathservice.getFileName());

        try {
            Files.copy(sourcePathservice, targetPathservice);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        //将code和对应的压缩包删除
        String message = "成功了哈哈哈哈";
        return success(message);
    }

    @Log(title = "查找数据库中所有新生成的表名")
    @GetMapping("/findTbale")
    public List<String> findTable(){
        List<String> table = sysAutomaticService.findTable();
            return table;
    }

    /**模板
     *
     * @param response
     */

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<NewCheck> util = new ExcelUtil<NewCheck>(NewCheck.class);
        util.importTemplateExcel(response, "用户数据");
    }


    /**
     * 查询自动生成列表
     */


    @PreAuthorize("@ss.hasPermi('check:automatic:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysAutomatic sysAutomatic)
    {
        startPage();
        List<SysAutomatic> list = sysAutomaticService.selectSysAutomaticList(sysAutomatic);
        return getDataTable(list);
    }

    /**
     * 导出自动生成列表
     */
    @PreAuthorize("@ss.hasPermi('check:automatic:export')")
    @Log(title = "自动生成", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysAutomatic sysAutomatic)
    {
        List<SysAutomatic> list = sysAutomaticService.selectSysAutomaticList(sysAutomatic);
        ExcelUtil<SysAutomatic> util = new ExcelUtil<SysAutomatic>(SysAutomatic.class);
        util.exportExcel(response, list, "自动生成数据");
    }

    /**
     * 获取自动生成详细信息
     */
    @PreAuthorize("@ss.hasPermi('check:automatic:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(sysAutomaticService.selectSysAutomaticById(id));
    }

    /**
     * 新增自动生成
     */
    @PreAuthorize("@ss.hasPermi('check:automatic:add')")
    @Log(title = "自动生成", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysAutomatic sysAutomatic)
    {
        return toAjax(sysAutomaticService.insertSysAutomatic(sysAutomatic));
    }

    /**
     * 修改自动生成
     */
    @PreAuthorize("@ss.hasPermi('check:automatic:edit')")
    @Log(title = "自动生成", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysAutomatic sysAutomatic)
    {
        return toAjax(sysAutomaticService.updateSysAutomatic(sysAutomatic));
    }

    /**
     * 删除自动生成
     */
    @PreAuthorize("@ss.hasPermi('check:automatic:remove')")
    @Log(title = "自动生成", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(sysAutomaticService.deleteSysAutomaticByIds(ids));
    }
    public static void copyFile(String sourceFilePath, String targetFilePath) throws IOException {
        File sourceFile = new File(sourceFilePath);
        File targetFile = new File(targetFilePath);
        FileInputStream inputStream = new FileInputStream(sourceFile);
        FileOutputStream outputStream = new FileOutputStream(targetFile);
        byte[] buffer = new byte[4096];
        int length = 0;
        while ((length = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, length);
        }
        inputStream.close();
        outputStream.close();
    }
    public static void copyFolder(String sourceFolderPath, String targetFolderPath) {
        File sourceFolder = new File(sourceFolderPath);
        String[] sourceFilePathList = sourceFolder.list();
        File targetFolder = new File(targetFolderPath);
        //判断目标文件夹是否存在,没有则创建
        if (!targetFolder.exists()) {
            targetFolder.mkdirs();
        }
        try {
            for (String filePath : sourceFilePathList) {
                if (new File(sourceFolderPath + sourceFolder.separator + filePath).isDirectory()) {
                    copyFolder(sourceFolderPath + sourceFolder.separator + filePath, targetFolderPath + sourceFolder.separator + filePath);
                }
                if (new File(sourceFolderPath + sourceFolder.separator + filePath).isFile()) {
                    copyFile(sourceFolderPath + sourceFolder.separator + filePath, targetFolderPath + sourceFolder.separator + filePath);
                }
            }
        } catch (IOException e) {
            System.out.println("复制文件夹信息出错");
        }
    }










}
